// forum.js - 论坛相关功能

// DOM元素
let newPostBtn;
let newPostModal;
let newPostForm;
let postError;
let postsList;
let pagination;
let forumContent;
let postDetail;
let backToPostsBtn;
let postTitle;
let postMeta;
let postContent;
let commentsList;
let commentContent;
let submitComment;

// 当前状态
let forumCurrentPage = 1;
let currentPostId = null;
let elementsInitialized = false;
let eventListenersSetup = false;
let forumModuleInitialized = false;

// 初始化DOM元素
function initForumElements() {
  // 重置事件监听器标志，因为DOM元素可能被重新创建
  eventListenersSetup = false;

  // 检查 Utils 是否可用
  if (!window.Utils) {
    console.error('window.Utils 不可用，这可能是脚本加载顺序问题');
    return false;
  }

  // 检查论坛页面是否可见
  const forumPage = document.getElementById('forum-page');
  if (!forumPage) {
    console.error('找不到论坛页面元素');
    return false;
  }

  // 重新获取所有DOM元素
  newPostBtn = document.getElementById('new-post-btn');
  postError = document.getElementById('post-error');
  postsList = document.getElementById('posts-list');
  pagination = document.getElementById('pagination');
  forumContent = document.querySelector('.forum-content');
  postDetail = document.getElementById('post-detail');
  backToPostsBtn = document.getElementById('back-to-posts-btn');
  postTitle = document.getElementById('post-title');
  postMeta = document.getElementById('post-meta');
  postContent = document.getElementById('post-content');
  commentsList = document.getElementById('comments-list');
  commentContent = document.getElementById('comment-content');
  submitComment = document.getElementById('submit-comment');

  // 检查关键元素是否存在
  if (!postsList || !newPostBtn) {
    console.error('关键DOM元素缺失:', { postsList: !!postsList, newPostBtn: !!newPostBtn });
    return false;
  }

  // 初始化模态框
  const modalElement = document.getElementById('new-post-modal');
  if (modalElement) {
    try {
      newPostModal = new bootstrap.Modal(modalElement);
      newPostForm = document.getElementById('new-post-form');
    } catch (err) {
      console.error('初始化新帖模态框失败:', err);
      return false;
    }
  } else {
    console.error('找不到新帖模态框元素');
    return false;
  }

  elementsInitialized = true;
  return true;
}

// 加载帖子列表
async function loadPosts(page = 1) {
  try {
    // 确保DOM元素已初始化
    if (!elementsInitialized && !initForumElements()) {
      return;
    }

    // 确保postsList存在
    if (!postsList) {
      postsList = document.getElementById('posts-list');
      if (!postsList) return;
    }

    // 显示加载状态
    window.Utils.safeSetInnerHTML(postsList, `
      <div class="text-center py-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>
      </div>
    `);

    const response = await fetch(`/api/posts?page=${page}`);
    if (!response.ok) {
      throw new Error(`获取帖子失败: ${response.status} ${response.statusText}`);
    }

    const data = await response.json();
    forumCurrentPage = page;

    // 清空现有内容
    postsList.innerHTML = '';

    if (!data.posts || data.posts.length === 0) {
      window.Utils.safeSetInnerHTML(postsList, '<div class="alert alert-info">暂无帖子，点击"发布新帖"按钮创建第一个帖子</div>');
      return;
    }

    // 渲染帖子列表
    data.posts.forEach(post => {
      const postElement = document.createElement('a');
      postElement.href = '#';
      postElement.className = 'list-group-item list-group-item-action post-item';
      postElement.dataset.postId = post.id;

      postElement.innerHTML = `
        <div class="d-flex w-100 justify-content-between">
          <h5 class="mb-1 post-title">${post.title}</h5>
          <small class="text-muted">${window.Utils.formatDate(post.created_at)}</small>
        </div>
        <div class="d-flex justify-content-between">
          <small class="post-meta">作者: ${post.username}</small>
        </div>
      `;

      postElement.addEventListener('click', (e) => {
        e.preventDefault();
        loadPostDetail(post.id);
      });

      postsList.appendChild(postElement);
    });

    // 渲染分页
    renderPagination(data);
  } catch (error) {
    console.error('加载帖子错误:', error);
    window.Utils.safeSetInnerHTML(postsList, `<div class="alert alert-danger">加载帖子失败: ${error.message}</div>`);
  }
}

// 渲染分页控件
function renderPagination(data) {
  // 确保分页元素存在
  if (!pagination) {
    pagination = document.getElementById('pagination');
    if (!pagination) return;
  }

  pagination.innerHTML = '';

  if (!data || !data.pages || data.pages <= 1) {
    return;
  }

  // 上一页按钮
  const prevLi = document.createElement('li');
  prevLi.className = `page-item ${forumCurrentPage === 1 ? 'disabled' : ''}`;
  prevLi.innerHTML = `<a class="page-link" href="#">上一页</a>`;

  if (forumCurrentPage > 1) {
    prevLi.addEventListener('click', (e) => {
      e.preventDefault();
      loadPosts(forumCurrentPage - 1);
    });
  }

  pagination.appendChild(prevLi);

  // 页码按钮
  for (let i = 1; i <= data.pages; i++) {
    const pageLi = document.createElement('li');
    pageLi.className = `page-item ${i === forumCurrentPage ? 'active' : ''}`;
    pageLi.innerHTML = `<a class="page-link" href="#">${i}</a>`;

    pageLi.addEventListener('click', (e) => {
      e.preventDefault();
      if (i !== forumCurrentPage) {
        loadPosts(i);
      }
    });

    pagination.appendChild(pageLi);
  }

  // 下一页按钮
  const nextLi = document.createElement('li');
  nextLi.className = `page-item ${forumCurrentPage === data.pages ? 'disabled' : ''}`;
  nextLi.innerHTML = `<a class="page-link" href="#">下一页</a>`;

  if (forumCurrentPage < data.pages) {
    nextLi.addEventListener('click', (e) => {
      e.preventDefault();
      loadPosts(forumCurrentPage + 1);
    });
  }

  pagination.appendChild(nextLi);
}

// 加载帖子详情
async function loadPostDetail(postId) {
  try {
    // 确保DOM元素已初始化
    if (!elementsInitialized && !initForumElements()) {
      return;
    }

    // 检查必要元素是否存在
    if (!postDetail || !forumContent || !postTitle || !postContent || !commentsList) {
      return;
    }

    // 显示加载状态
    postDetail.classList.remove('d-none');
    forumContent.classList.add('d-none');

    postTitle.textContent = '加载中...';
    postContent.textContent = '';
    window.Utils.safeSetInnerHTML(commentsList, `
      <div class="text-center py-3">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>
      </div>
    `);

    const response = await fetch(`/api/posts/${postId}`);
    if (!response.ok) {
      throw new Error('获取帖子详情失败');
    }

    const post = await response.json();
    currentPostId = post.id;

    // 更新帖子详情
    postTitle.textContent = post.title || '无标题';
    postMeta.textContent = `${post.username || '未知用户'} · ${window.Utils.formatDate(post.created_at)}`;
    postContent.textContent = post.content || '无内容';

    // 渲染评论
    renderComments(post.comments || []);

    // 滚动到顶部
    window.scrollTo(0, 0);
  } catch (error) {
    console.error('加载帖子详情错误:', error);
    if (postDetail) {
      window.Utils.safeSetInnerHTML(postDetail, `
        <div class="alert alert-danger">加载帖子详情失败: ${error.message}</div>
        <button class="btn btn-outline-secondary" id="back-btn">返回帖子列表</button>
      `);

      const backBtn = document.getElementById('back-btn');
      if (backBtn) {
        backBtn.addEventListener('click', () => {
          showPostsList();
        });
      }
    }
  }
}

// 渲染评论
function renderComments(comments) {
  if (!commentsList) return;

  commentsList.innerHTML = '';

  if (comments.length === 0) {
    commentsList.innerHTML = '<div class="text-center text-muted py-3">暂无评论</div>';
    return;
  }

  comments.forEach(comment => {
    const commentElement = document.createElement('div');
    commentElement.className = 'comment';

    commentElement.innerHTML = `
      <div class="comment-header">
        <span class="comment-author">${comment.username || '未知用户'}</span>
        <small class="comment-date">${window.Utils.formatDate(comment.created_at)}</small>
      </div>
      <div class="comment-content">
        ${comment.content || ''}
      </div>
    `;

    commentsList.appendChild(commentElement);
  });
}

// 返回帖子列表
function showPostsList() {
  if (!postDetail || !forumContent) return;

  postDetail.classList.add('d-none');
  forumContent.classList.remove('d-none');
  currentPostId = null;
}

// 发布新帖
async function createPost(title, content) {
  try {
    const response = await fetch('/api/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ title, content }),
      credentials: 'include',
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || '发布帖子失败');
    }

    // 隐藏模态框，重置表单
    newPostModal.hide();
    newPostForm.reset();

    // 重新加载帖子列表
    loadPosts(1);

    return data;
  } catch (error) {
    console.error('创建帖子错误:', error);
    postError.textContent = error.message;
    postError.classList.remove('d-none');
    throw error;
  }
}

// 发布评论
async function createComment(postId, content) {
  try {
    const response = await fetch(`/api/posts/${postId}/comments`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ content }),
      credentials: 'include',
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || '发布评论失败');
    }

    // 重新加载帖子详情以查看新评论
    loadPostDetail(postId);

    // 清空评论框
    commentContent.value = '';

    return data;
  } catch (error) {
    alert('发布评论失败: ' + error.message);
    throw error;
  }
}

// 设置事件监听
function setupEventListeners() {
  // 防止重复设置事件监听器
  if (eventListenersSetup) {
    return;
  }

  if (!newPostBtn) {
    return;
  }

  newPostBtn.addEventListener('click', () => {
    // 检查 Auth 模块
    if (!window.Auth) {
      alert('认证模块未加载，请刷新页面重试');
      return;
    }

    if (!window.Auth.isLoggedIn()) {
      alert('请先登录');
      return;
    }

    if (!newPostModal) {
      const modalElement = document.getElementById('new-post-modal');
      if (modalElement) {
        try {
          newPostModal = new bootstrap.Modal(modalElement);
        } catch (err) {
          alert('系统错误，无法创建新帖');
          return;
        }
      } else {
        alert('系统错误，无法创建新帖');
        return;
      }
    }

    if (postError) {
      postError.classList.add('d-none');
    }

    try {
      newPostModal.show();
    } catch (err) {
      alert('无法显示新帖对话框');
    }
  });

  if (newPostForm) {
    newPostForm.addEventListener('submit', async (e) => {
      e.preventDefault();

      const title = document.getElementById('post-title-input').value;
      const content = document.getElementById('post-content-input').value;

      if (postError) {
        postError.classList.add('d-none');
      }

      try {
        await createPost(title, content);
      } catch (error) {
        // 错误已在createPost中处理
      }
    });
  }

  if (backToPostsBtn) {
    backToPostsBtn.addEventListener('click', (e) => {
      e.preventDefault();
      showPostsList();
    });
  }

  if (submitComment) {
    submitComment.addEventListener('click', async () => {
      if (!window.Auth || !window.Auth.isLoggedIn()) {
        alert('请先登录');
        return;
      }

      if (!commentContent) {
        return;
      }

      const content = commentContent.value.trim();

      if (!content) {
        alert('评论内容不能为空');
        return;
      }

      if (!currentPostId) {
        alert('未找到当前帖子');
        return;
      }

      try {
        await createComment(currentPostId, content);
      } catch (error) {
        // 错误已在createComment中处理
      }
    });
  }

  // 标记事件监听器已设置
  eventListenersSetup = true;
}

// 初始化论坛模块
function initForum() {
  // 防止重复初始化
  if (forumModuleInitialized) {
    return;
  }

  try {
    // 论坛页面显示时加载帖子
    document.addEventListener('pageChanged', (e) => {
      if (e.detail.page === 'forum') {
        // 使用延迟确保DOM已完全渲染
        setTimeout(() => {
          // 确保论坛页面可见
          const forumPage = document.getElementById('forum-page');
          if (forumPage && forumPage.classList.contains('d-none')) {
            return;
          }

          if (initForumElements()) {
            setupEventListeners();
            loadPosts(1);
          } else {
            // 尝试在页面上显示错误
            const forumPage = document.getElementById('forum-page');
            if (forumPage) {
              forumPage.innerHTML = '<div class="alert alert-danger">加载论坛失败: 无法初始化必要组件</div>';
            }
          }
        }, 500);
      }
    });

    forumModuleInitialized = true;
  } catch (err) {
    console.error('初始化论坛模块错误:', err);
  }
}

// 手动触发一次初始化
document.addEventListener('DOMContentLoaded', () => {
  // 初始化论坛模块
  initForum();

  setTimeout(() => {
    // 检查当前页面是否是论坛
    const forumPage = document.getElementById('forum-page');
    if (forumPage) {
      const isVisible = !forumPage.classList.contains('d-none');

      if (isVisible) {
        if (initForumElements()) {
          setupEventListeners();
          loadPosts(1);
        }
      }
    }
  }, 1000);
});

// 导出函数供其他模块使用
window.Forum = {
  loadPosts,
  loadPostDetail,
  createPost: function (title, content) {
    if (newPostModal) {
      newPostModal.hide();
    }
    return createPost(title, content);
  },
  openNewPostModal: function () {
    if (!newPostModal) {
      const modalElement = document.getElementById('new-post-modal');
      if (modalElement) {
        newPostModal = new bootstrap.Modal(modalElement);
      } else {
        debug('找不到新帖模态框元素');
        alert('系统错误，无法创建新帖');
        return;
      }
    }
    newPostModal.show();
  }
};